import request from '@/utils/request'
import { Md5 } from 'ts-md5'
import { eachTree } from 'xe-utils'

/**
 * 登录api接口集合
 * @method signIn 用户登录
 * @method signOut 用户退出登录
 * @method signUserInfo 获取用户信息
 * @method signChangePwd 修改密码
 */
export function useLoginApi() {
  return {
    signIn: async (data: LoginForm) => {
      const md5: Md5 = new Md5()
      md5.appendStr(data.password.trim())
      const password = md5.end()
      return request<{ token: string }>({
        url: '/api-base/Auth/login',
        method: 'post',
        data: {
          username: data.username,
          password
        }
      })
    },
    signOut: (data: object) => {
      return request({
        url: '/api-base/Auth/logout',
        method: 'post',
        data
      })
    },
    signUserInfo: async () => {
      return request<{ user: UserInfos; business: RouteItem[] }>({
        url: '/api-base/Auth/userinfo',
        method: 'get'
      }).then((res) => {
        // 将废弃 TemplateTable 模板 替换为 TemplateGrid
        eachTree(res.data.business, (item) => {
          if (item.component === '/components/TemplateTable.vue') {
            item.component = '/components/grid/TemplateGrid.vue'
          }
        })
        return res
      })
    },
    signChangePwd: async (data: object) => {
      return request({
        url: '/api-base/Auth/chagne_pwd',
        method: 'post',
        data
      })
    }
  }
}
